// 全局变量
let currentPage = 1;
let pageSize = 10;
let totalPages = 0;
let selectedItems = [];

// 页面加载完成后初始化
$(document).ready(function () {
    let currentPage = 1;
    let pageSize = 10;
    let totalPages = 0;
    let inventoryData = [];

    // 初始化页面
    initPage();

    function initPage() {
        loadInventoryData();
        bindEvents();
    }

    function bindEvents() {
        // 搜索按钮
        $('#searchBtn').click(function () {
            currentPage = 1;
            loadInventoryData();
        });

        // 重置按钮
        $('#resetBtn').click(function () {
            $('#searchForm')[0].reset();
            currentPage = 1;
            loadInventoryData();
        });

        // 新增按钮
        $('#addBtn').click(function () {
            showAddModal();
        });

        // 删除按钮
        $('#deleteBtn').click(function () {
            deleteSelectedItems();
        });

        // 导出按钮
        $('#exportBtn').click(function () {
            exportData();
        });

        // 作废按钮
        $('#voidBtn').click(function () {
            voidSelectedItems();
        });

        // 锁定仓库按钮
        $('#lockBtn').click(function () {
            lockWarehouse();
        });

        // 刷新按钮
        $('#refreshBtn').click(function () {
            loadInventoryData();
        });

        // 保存新增/编辑
        $('#saveInventoryBtn').click(function () {
            saveInventory();
        });

        // 分页事件
        $(document).on('click', '.pagination .page-link', function (e) {
            e.preventDefault();
            const page = $(this).data('page');
            if (page && page !== currentPage) {
                currentPage = page;
                loadInventoryData();
            }
        });
    }

    function loadInventoryData() {
        const searchData = {
            reviewNo: $('#reviewNo').val(),
            reviewType: $('#reviewType').val(),
            warehouseId: $('#warehouseId').val(),
            startTime: $('#startTime').val(),
            endTime: $('#endTime').val(),
            status: $('#status').val()
        };

        const pageData = {
            pageIndex: currentPage,
            pageSize: pageSize,
            keyword: searchData.reviewNo || searchData.reviewType || searchData.warehouseId || ''
        };

        // 使用ABP框架的约定式API端点
        $.ajax({
            url: '/api/app/review-services/get-review-page',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(pageData),
            success: function (response) {
                if (response.code === 200) {
                    inventoryData = response.resultData || [];
                    totalPages = Math.ceil(response.total / pageSize);
                    renderInventoryTable();
                    renderPagination();
                } else {
                    showError('加载数据失败：' + response.message);
                }
            },
            error: function (xhr, status, error) {
                showError('加载数据失败：' + error);
            }
        });
    }

    function renderInventoryTable() {
        const tbody = $('#inventoryTable tbody');
        tbody.empty();

        if (inventoryData.length === 0) {
            tbody.append('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
            return;
        }

        inventoryData.forEach(function (item) {
            const row = `
                <tr>
                    <td><input type="checkbox" class="item-checkbox" value="${item.id}"></td>
                    <td>${item.reviewNo || ''}</td>
                    <td>${item.reviewType || ''}</td>
                    <td>${item.warehouseid || ''}</td>
                    <td>${formatDateTime(item.startTime)}</td>
                    <td>${formatDateTime(item.endTime)}</td>
                    <td>${getStatusText(item.rstauts)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="editInventory('${item.reviewNo}')">编辑</button>
                        <button class="btn btn-sm btn-info" onclick="viewDetails('${item.reviewNo}')">明细</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteInventory('${item.id}')">删除</button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    function renderPagination() {
        const pagination = $('#pagination');
        pagination.empty();

        if (totalPages <= 1) return;

        let paginationHtml = '<ul class="pagination">';
        
        // 上一页
        if (currentPage > 1) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a></li>`;
        }

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                paginationHtml += `<li class="page-item active"><span class="page-link">${i}</span></li>`;
            } else {
                paginationHtml += `<li class="page-item"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
            }
        }

        // 下一页
        if (currentPage < totalPages) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a></li>`;
        }

        paginationHtml += '</ul>';
        pagination.html(paginationHtml);
    }

    function showAddModal() {
        $('#inventoryModal .modal-title').text('新增盘点单');
        $('#inventoryModal').modal('show');
        $('#inventoryForm')[0].reset();
    }

    function saveInventory() {
        const formData = {
            reviewType: $('#modalReviewType').val(),
            warehouseid: $('#modalWarehouseId').val(),
            startTime: $('#modalStartTime').val(),
            endTime: $('#modalEndTime').val(),
            userId: getCurrentUserId(), // 获取当前用户ID
            remark: $('#modalRemark').val(),
            rstauts: 1 // 默认状态
        };

        // 使用ABP框架的约定式API端点
        $.ajax({
            url: '/api/app/review-services/add-review',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function (response) {
                if (response.code === 200) {
                    showSuccess('保存成功');
                    $('#inventoryModal').modal('hide');
                    loadInventoryData();
                } else {
                    showError('保存失败：' + response.message);
                }
            },
            error: function (xhr, status, error) {
                showError('保存失败：' + error);
            }
        });
    }

    function deleteSelectedItems() {
        const selectedIds = [];
        $('.item-checkbox:checked').each(function () {
            selectedIds.push($(this).val());
        });

        if (selectedIds.length === 0) {
            showWarning('请选择要删除的项目');
            return;
        }

        if (confirm('确定要删除选中的项目吗？')) {
            // 批量删除
            const promises = selectedIds.map(id => 
                $.ajax({
                    url: `/api/app/review-services/delete-review/${id}`,
                    type: 'DELETE'
                })
            );

            Promise.all(promises).then(function () {
                showSuccess('删除成功');
                loadInventoryData();
            }).catch(function (error) {
                showError('删除失败：' + error);
            });
        }
    }

    function deleteInventory(id) {
        if (confirm('确定要删除这条记录吗？')) {
            $.ajax({
                url: `/api/app/review-services/delete-review/${id}`,
                type: 'DELETE',
                success: function (response) {
                    if (response.code === 200) {
                        showSuccess('删除成功');
                        loadInventoryData();
                    } else {
                        showError('删除失败：' + response.message);
                    }
                },
                error: function (xhr, status, error) {
                    showError('删除失败：' + error);
                }
            });
        }
    }

    function editInventory(reviewNo) {
        // 跳转到编辑页面
        window.location.href = `/Inventory/Edit?reviewNo=${reviewNo}`;
    }

    function viewDetails(reviewNo) {
        // 跳转到明细页面
        window.location.href = `/Inventory/Detail?reviewNo=${reviewNo}`;
    }

    function exportData() {
        // 导出功能实现
        showInfo('导出功能开发中...');
    }

    function voidSelectedItems() {
        // 作废功能实现
        showInfo('作废功能开发中...');
    }

    function lockWarehouse() {
        // 锁定仓库功能实现
        showInfo('锁定仓库功能开发中...');
    }

    // 工具函数
    function formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return '';
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN');
    }

    function getStatusText(status) {
        const statusMap = {
            1: '待盘点',
            2: '盘点中',
            3: '已完成',
            4: '已作废'
        };
        return statusMap[status] || '未知';
    }

    function getCurrentUserId() {
        // 获取当前用户ID，这里需要根据实际的用户认证系统实现
        return '00000000-0000-0000-0000-000000000001'; // 临时返回固定值
    }

    function showSuccess(message) {
        // 显示成功消息
        alert('成功：' + message);
    }

    function showError(message) {
        // 显示错误消息
        alert('错误：' + message);
    }

    function showWarning(message) {
        // 显示警告消息
        alert('警告：' + message);
    }

    function showInfo(message) {
        // 显示信息消息
        alert('信息：' + message);
    }
});

// 全局函数，供HTML调用
function editInventory(reviewNo) {
    window.location.href = `/Inventory/Edit?reviewNo=${reviewNo}`;
}

function viewDetails(reviewNo) {
    window.location.href = `/Inventory/Detail?reviewNo=${reviewNo}`;
}

function deleteInventory(id) {
    if (confirm('确定要删除这条记录吗？')) {
        $.ajax({
            url: `/api/app/review-services/delete-review/${id}`,
            type: 'DELETE',
            success: function (response) {
                if (response.code === 200) {
                    alert('删除成功');
                    location.reload();
                } else {
                    alert('删除失败：' + response.message);
                }
            },
            error: function (xhr, status, error) {
                alert('删除失败：' + error);
            }
        });
    }
} 